package com.icw.resource.inner.module.srv;

import com.icw.resource.inner.entity.IcwSysParam;
import com.icw.utility.BeanCtxUtils;

import javax.persistence.EntityManager;

import com.icw.decoupling.impl.module.GenericSrvImpl;

public class IcwSysParamRestfulService extends GenericSrvImpl<IcwSysParam> {

	@Override
	public String getNameFieldName() throws Exception {
		return "name";
	}

	@Override
	public IcwSysParam findByName(String name) throws Exception {
		String[] nameSplt = name.split(",");
		String key = nameSplt[0];
		String value = nameSplt.length == 2 ? nameSplt[1] : null;
		EntityManager em = BeanCtxUtils.getBeanByType(EntityManager.class);
		int affectCount = em.createNativeQuery("update icw_sys_param set value = cast(value as SIGNED) + 1 where name = ?").setParameter(1, key).executeUpdate();
		if (affectCount == 0) {
			IcwSysParam s = new IcwSysParam();
			s.setName(key);
			s.setValue(value);
			save(s);
			return s;
		} else if (affectCount == 1) {
			return super.findByName(key);
		} else {
			throw new Exception("Duplicate SysParam[name=" + key + "]");
		}
	}
}
